package com.bahiaapk.services;

import org.json.JSONArray;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import blueprint.software.blueframe.synchronize.HTTPConnect;
import com.bahiaapk.dao.NewsDAO;
import com.bahiaapk.util.BahiaUtil;

public class SynchronizeNews implements Runnable {
	 
	 private Handler handler;
	 private Context context;
	 private HTTPConnect connect;
	 private NewsDAO dao;
	 private final Thread thread = new Thread(this);

	 public void synchronize(Context context, Handler handler){
		 
		 this.handler = handler;
		 this.context= context;
		 dao = new NewsDAO(context);
		 thread.start();
	 }
	@Override
	public void run() {
		Bundle data = new Bundle();
		
		if(BahiaUtil.haveNetworkConnection(context)){
			try{
				connect = new HTTPConnect(BahiaUtil.urlServer+"/getNews");
				JSONArray jsonArray =  connect.getArray("", null);
			
				if(jsonArray!=null && jsonArray.length()>0){
					dao.insert(jsonArray);
					dao.removeInactive();
					
				}
	    	}catch (Exception e) {
				Log.e(BahiaUtil.TAG, e.toString());
			}
		}
		
		data.putBoolean("status", true);
		
		// Add the data to a Message
		Message msg = new Message();
		msg.setData(data);
						
		// Send the Message with the data to the Handler
		handler.sendMessage(msg);		
	}
}